package com.jcl.recruit.wechat.logic;

import com.jcl.core.utils.CollectionUtils;
import com.jcl.core.utils.EncodeMd;
import com.jcl.core.utils.HttpRequest;
import com.jcl.recruit.attach.vo.AttachmentPhotoVo;
import com.jcl.recruit.console.logic.ConsoleUserAccessLogic;
import com.jcl.recruit.console.model.ConsoleUserAccess;
import com.jcl.recruit.core.config.SystemConfig;
import com.jcl.recruit.core.constants.Constants;
import com.jcl.recruit.core.constants.UserExternalLoginConstant;
import com.jcl.recruit.basic.login.model.UserExternalLoginInfo;
import com.jcl.recruit.user.logic.UserLogic;
import com.jcl.recruit.user.model.User;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/**
 * @ClassName WechatLoginLogic

 * @Author yyliu
 * @Date 2018/10/24 13:59
 * @Version 1.0
 **/
@Component
public class WechatAccessLogic {

    @Autowired
    private ConsoleUserAccessLogic consoleUserAccessLogic;

    @Autowired
    private WechatCommonLogic wechatCommonLogic;

    @Autowired
    private UserLogic userLogic;

    public UserExternalLoginInfo accessLogin(WechatUtils.WechatUserInfo userInfo) {
        // 登录
        UserExternalLoginInfo userExternalLoginInfo = new UserExternalLoginInfo();
        List<ConsoleUserAccess> accessList = consoleUserAccessLogic.findListByExternalKey( userInfo.getOpenid(),
                UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
        ConsoleUserAccess userAccess = null;
        if (CollectionUtils.isNotEmpty(accessList)) {
            userAccess = accessList.get(0);
        }
        // 用户不存在， 创建用户到 默认企业
        if(null == userAccess){
            userAccess = this.registerDefault(userInfo.getCorpCode(), userInfo.getOpenid(),
                    userInfo.getUnionid(), userInfo.getNickname(), userInfo.getHeadimgurl());
        }
        userExternalLoginInfo = new UserExternalLoginInfo();
        userExternalLoginInfo.setUsername(userAccess.getUsername());
        userExternalLoginInfo.setPassword(userAccess.getPassword());
        userExternalLoginInfo.setUserId(userAccess.getUserId());
        userExternalLoginInfo.setCorpCode(userAccess.getCorpCode());
        return userExternalLoginInfo;
    }


    public ConsoleUserAccess addTempUserAccess(String externalKey,
                                                       String externalUnionKey,
                                                       String nickname,
                                                       String category,
                                                       Integer status){
        ConsoleUserAccess userAccess = new ConsoleUserAccess();
        userAccess.setExternalKey(externalKey);
        userAccess.setExternalUnionKey(externalUnionKey);
        userAccess.setNickname(nickname);
        userAccess.setCategory(category);
        userAccess.setStatus(status);
        userAccess.setUsername(externalKey + UserExternalLoginConstant.USER_ACCESS_SPLIT
                + System.currentTimeMillis());
        try {
            userAccess.setPassword(EncodeMd.EncodeByMd5(SystemConfig.getDefaultPassword()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        userAccess.setCreateTime(new Date());
        userAccess.setUpdateTime(new Date());
        consoleUserAccessLogic.add(userAccess);
        return userAccess;
    }

    public UserExternalLoginInfo loginByExternalKey(String externalKey, String category) {

        // 查询正在使用的 账号
        List<ConsoleUserAccess> accessList = consoleUserAccessLogic.findListByExternalKey(
                externalKey, category, UserExternalLoginConstant.USER_ACCESS_STATUS_USED);
        if (CollectionUtils.isNotEmpty(accessList)) {
            ConsoleUserAccess userExternalAccess = accessList.get(0);
            UserExternalLoginInfo userExternalLoginInfo = makeUserExternalLoginInfo(userExternalAccess);
            return userExternalLoginInfo;
        }
        return null;
    }


    public ConsoleUserAccess registerDefault(String corpCode,
                                String openid,
                                String unionId,
                                String nickName,
                                String headImgUrl){
        // 用户不存在， 创建用户到 默认企业
        ConsoleUserAccess userAccess = this.addDefaultUserAccess(corpCode, openid, unionId, nickName,
                UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT,
                UserExternalLoginConstant.USER_ACCESS_STATUS_USED);

        User user = this.addDefaultUser(corpCode, nickName);
        userAccess.setUserId(user.getId());
        consoleUserAccessLogic.updateAccess(userAccess);

        if(false){
            byte[] b = HttpRequest.getByte(headImgUrl);
            AttachmentPhotoVo vo = new AttachmentPhotoVo();
            vo.setBytes(b);
            vo.setFileName(openid);

            wechatCommonLogic.updateUserHead(vo, user.getId(), user.getCorpCode());
        }
        return userAccess;
    }

    public ConsoleUserAccess addDefaultUserAccess(String corpCode,
                                                   String externalKey,
                                                   String externalUnionKey,
                                                   String nickname,
                                                   String category,
                                                   Integer status) {
        ConsoleUserAccess userAccess = new ConsoleUserAccess();
        userAccess.setExternalKey(externalKey);
        userAccess.setExternalUnionKey(externalUnionKey);
        userAccess.setNickname(nickname);
        userAccess.setCategory(category);
        userAccess.setStatus(status);
        userAccess.setUsername(externalKey
                + UserExternalLoginConstant.USER_ACCESS_SPLIT + corpCode);
        try {
            userAccess.setPassword(EncodeMd.EncodeByMd5(SystemConfig.getDefaultPassword()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        userAccess.setCorpCode(corpCode);
        userAccess.setCreateTime(new Date());
        userAccess.setUpdateTime(new Date());
        consoleUserAccessLogic.add(userAccess);

        return userAccess;
    }

    public User addDefaultUser(String corpCode, String nickName){
        User user = new User();
        user.setRealname(nickName);
        user.setCorpCode(corpCode);
        user.setDepartId(Constants.DepartmentInfo.DEFAULT_TRY_ID);
        try {
            user.setPassword(EncodeMd.EncodeByMd5(SystemConfig.getDefaultPassword()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        user.setCreateTime(new Date());
        user.setStatus(Constants.UserInfo.USER_STATUS_ACTIVE);
        user.setRoles(Constants.UserInfo.createHrRole());
        userLogic.insertSelective(user);
        return user;
    }

    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 9:43 2018/10/19
     * @Param [externalAccess]
     * @return com.example.logic.login.UserExternalLoginInfo
     **/
    private UserExternalLoginInfo makeUserExternalLoginInfo(ConsoleUserAccess externalAccess) {
        UserExternalLoginInfo info = new UserExternalLoginInfo();
        info.setUsername(externalAccess.getUsername());
        info.setPassword(externalAccess.getPassword());
        info.setUserId(externalAccess.getUserId());
        info.setCorpCode(externalAccess.getCorpCode());
        return info;
    }
}
